package cn.changhong.user.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Author zz
 * @Date
 **/
@Aspect
@Component
public class WebLogAspect {
     Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(public * cn.changhong.user.controller..*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

    }
    //后置通知，包括异常
    @After("webLog()")
    public void doAfter(){
        System.out.println("后置通知，包括异常");
    }

    //声明例外通知
    @AfterThrowing(pointcut="webLog()",throwing = "e")
    public void doAfterThrowing(Exception e){
        logger.error(e.getMessage());
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("RESPONSE : " + ret);
    }

    //声明环绕通知
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        logger.info("进入方法---环绕通知");
        logger.info(pjp.getTarget().getClass().getName());
        Object o = pjp.proceed();
        logger.info("退出方法---环绕通知");
        return o;
    }

}
